package cn.itsource.basic.aop;

import cn.itsource.basic.annotation.Repeat;
import cn.itsource.basic.config.exception.BusinessException;
import cn.itsource.basic.util.RedisService;
import lombok.extern.slf4j.Slf4j;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Before;
import org.aspectj.lang.annotation.Pointcut;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import javax.servlet.http.HttpServletRequest;

@Aspect //声明这是一个切面类
@Component //交给spring管理
@Slf4j    //日志操作  log对象可以用
public class RepeatAop {

    @Autowired
    private RedisService redisService;

    /**
     * 语法
     * 切点 （何地）
     * @annotation(repeat): 管理配置了注解（Repeat repeat）的方法
     */
    @Pointcut("@annotation(repeat)")
    public void cut111(Repeat repeat){

    }

    /**
     * 在执行目标之前
     * @param repeat
     *
     * 切面
     * www.baidu.com
     */
    @Before("cut111(repeat)")
    public void repeat(Repeat repeat){
        //1.获取request对象
        HttpServletRequest request = ((ServletRequestAttributes) RequestContextHolder.getRequestAttributes()).getRequest();

        //2.获取
        //3.拦截同一个ip一直获取验证码
        String ipPhoneStr = request.getRemoteAddr() + request.getRequestURI();

        String res = redisService.getKeyObjectValue(ipPhoneStr, String.class);
        if (res != null){
            throw new BusinessException("兄die,你不正常.111..");
        }
        //存ip到redis中,保持1分钟,1分钟内重复获取抛出上面的异常
        redisService.setStringKeyAndValue(ipPhoneStr,"123456",repeat.value());

    }

}